<template>
  <a-drawer
      :title="title"
      :maskClosable="true"
      :visible="visible"
      :destroyOnClose="true"
      :width="450"
      :body-style="{ paddingBottom: '80px' }"
      @close="closeModal"
  >
    <a-form layout="vertical">
      <a-form-item label="条目名称" v-bind="validateInfos.name">
        <a-input placeholder="请输入条目名称" v-model:value="modelRef.name"/>
      </a-form-item>
      <a-form-item label="收款公司" v-bind="validateInfos.org_branch_id">
        <a-select
            style="width: 100%"
            :allowClear="true"
            placeholder="请选择收款公司"
            v-model:value="modelRef.org_branch_id"
            :options="branchCompanyOptions"
        />
      </a-form-item>
      <a-form-item v-bind="validateInfos.is_company">
        <template #label>
          <span>账户类型</span>
          <text-tip tips="账单只匹配个户流水则不支持开票"/>
        </template>
        <a-radio-group v-model:value="modelRef.is_company" name="radioGroup">
          <a-radio :value="1">公司</a-radio>
          <a-radio :value="0">个人</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="账户名称" v-bind="validateInfos.account_name">
        <a-input placeholder="请输入账户名称" v-model:value="modelRef.account_name"/>
      </a-form-item>
      <a-form-item label="开户银行" v-bind="validateInfos.bank">
        <a-input placeholder="请输入开户银行" v-model:value="modelRef.bank"/>
      </a-form-item>
      <a-form-item label="银行账号" v-bind="validateInfos.bank_account">
        <a-input
            placeholder="请输入银行账号"
            v-model:value="modelRef.bank_account"
        />
      </a-form-item>
      <a-form-item label="总分类账科目" v-bind="validateInfos.subject">
        <a-input
            placeholder="请输入总分类账科目"
            v-model:value="modelRef.subject"
        />
      </a-form-item>
      <a-form-item label="状态" v-bind="validateInfos.status">
        <a-switch
            :checkedValue="1"
            :unCheckedValue="0"
            v-model:checked="modelRef.status"
            checked-children="开启"
            un-checked-children="关闭"
        />
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="closeModal">取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
      </a-space>
    </div>
  </a-drawer>
</template>

<script>
import {computed, defineComponent, reactive, ref, toRaw, toRefs, watch} from "vue";
import {Form, message} from "ant-design-vue";
import utils from "../../../../common/utils/utils";
import request from "../../../../common/utils/request";
import {TextTip} from "bl-common-vue3";

const useForm = Form.useForm;

export default defineComponent({
  name: "AccountAdd",
  components: {TextTip,},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, {emit}) {
    /**
     * @description: 标题显示
     */
    const title = computed(() => {
      return props.id ? "编辑收支账户" : "新增收支账户";
    });

    const state = reactive({
      branchCompanyOptions: [],
    });

    /**
     * @description: 触发关闭
     */
    const closeModal = () => {
      emit("cancel");
    };

    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      name: "",
      is_company: 1,
      bank: "",
      bank_account: "",
      account_name: "",
      subject: "",
      status: 1,
      org_branch_id: undefined,
    });

    const requiredRule = [{required: true, message: "必填项"}];

    /**
     * @description: 验证规则
     */
    const rulesRef = reactive({
      name: requiredRule,
      org_branch_id: requiredRule,
      is_company: requiredRule,
      account_name: requiredRule,
      bank: requiredRule,
      bank_account: [
        {
          required: true,
          validator: (rules, value) =>
              utils.numberValidator(rules, value, "请填写正确的银行账号"),
          trigger: "change",
        },
      ],
      status: requiredRule,
    });

    /**
     * @description: 创建表单
     */
    const {resetFields, validate, validateInfos} = useForm(
        modelRef,
        rulesRef
    );

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      validate().then(() => {
        let params = {...toRaw(modelRef), needMsg: true};
        if (props.id) {
          params.id = props.id;
        }
        let requestMethod = props.id ? "put" : "post";
        request[requestMethod]("/org", "/manage/account", params).then(
            (res) => {
              message.success(res.msg || "保存成功");
              emit("success");
            }
        );
      });
    };

    /**
     * @description: 获取编辑信息
     */
    const getEditInfo = () => {
      request
          .get("/org", "/manage/account/get", {id: props.id})
          .then((res) => {
            const {detail} = res;
            setModelRef({
              name: detail.name,
              bank: detail.bank,
              bank_account: detail.bank_account,
              account_name: detail.account_name,
              subject: detail.subject,
              status: detail.status,
              org_branch_id: detail.org_branch_id,
              is_company: !detail.is_company || detail.is_company == 0 ? 0 : detail.is_company,
            });
          });
    };

    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };

    const getCompany = () => {
      request.get("/org", "/company/orgAndBranch",)
          .then((res) => {
            state.branchCompanyOptions = (res?.list || []).map((item) => {
              return {
                value: item.id,
                label: item.company,
              }
            });
            if (!props.id) {
              // 新增 -- 默认总公司账户
              modelRef.org_branch_id = (res?.list || []).find((v) => v.is_system == 1)?.id || undefined;
              modelRef.account_name = (res?.list || []).find((v) => v.is_system == 1)?.company || "";
            }
          })
    };

    /**
     * @description: 初始化
     */
    const init = () => {
      getCompany();
      if (props.id) {
        getEditInfo();
      }
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            // 打开时初始化数据
            init();
          } else {
            // 关闭时重置数据
            resetFields();
          }
        }
    );
    return {
      title,
      ...toRefs(state),
      validateInfos,
      modelRef,
      resetFields,
      closeModal,
      onSubmit,
    };
  },
});
</script>
